package com.suixin.learn.persistence.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.suixin.learn.persistence.io.Resources;
import com.suixin.learn.persistence.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XmlConfigBuilder {

    public Configuration parseConfig(InputStream in) throws DocumentException, PropertyVetoException {
        Configuration configuration = new Configuration();
        Document read = new SAXReader().read(in);
        Element root = read.getRootElement();
        List<Element> list = root.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            properties.setProperty(element.attributeValue("name"),element.attributeValue("value"));
        }
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configuration.setDataSource(comboPooledDataSource);

        List<Element> mapperList = root.selectNodes("//mapper");
        for(Element mapper : mapperList){
            String resource = mapper.attributeValue("resource");
            InputStream mapperIn = Resources.getResource(resource);
            XmlMapperBuilder xmlMapperBuilder = new XmlMapperBuilder(configuration);
            xmlMapperBuilder.parse(mapperIn);
        }

        return configuration;
    }
}
